package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.EncryptAesUtil;
import com.ruoyi.common.core.utils.QRCodeUtils;
import com.ruoyi.common.core.utils.ShareCodeUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.db.domain.system.*;
import com.ruoyi.db.domain.system.dto.MpClientFriendCount;
import com.ruoyi.db.domain.web.MpClientTransfer;
import com.ruoyi.db.domain.web.MpIncomeRecord;
import com.ruoyi.db.domain.web.dto.MpRegistForm;
import com.ruoyi.db.mapper.system.*;
import com.ruoyi.db.mapper.web.MpIncomeRecordMapper;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IMpClientService;

import javax.transaction.Transactional;

/**
 * 【商城用户】Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-22
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class MpClientServiceImpl implements IMpClientService
{
    @Autowired
    private MpClientMapper mpClientMapper;
    @Autowired
    private MpClientFriendsMapper mpClientFriendsMapper;
    @Autowired
    private PcTeamConfigMapper pcTeamConfigMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private PcCompanyConfigMapper pcCompanyConfigMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PcUserClientFriendsMapper pcUserClientFriendsMapper;
    @Autowired
    private MpClientRaiseRecordMapper mpClientRaiseRecordMapper;
    @Autowired
    private MpClientOrderMapper mpClientOrderMapper;
    @Autowired
    private MpIncomeRecordMapper mpIncomeRecordMapper;
    @Autowired
    private PcUserEarnsMapper pcUserEarnsMapper;
    @Autowired
    private MpCashApplyMapper mpCashApplyMapper;

    /**
     * 查询【商城用户】
     *
     * @param clientId 【商城用户】主键
     * @return 【商城用户】
     */
    @Override
    public MpClient selectMpClientByClientId(Long clientId)
    {
        return mpClientMapper.selectMpClientByClientId(clientId);
    }

    /**
     * 查询【商城用户】列表
     *
     * @param mpClient 【商城用户】
     * @return 【商城用户】
     */
    @Override
    public List<MpClient> selectMpClientList(MpClient mpClient)
    {
        if(mpClient.getStartTime()!=null){
            String startTime = mpClient.getRegistTime()+ " 00:00:00";
            String endTime = mpClient.getRegistTime() + " 23:59:59";
            mpClient.setStartTime(startTime);
            mpClient.setEndTime(endTime);
        }
        List<MpClient> list = mpClientMapper.selectMpClientList(mpClient);

        for (MpClient client:list) {
             client.setPassword(EncryptAesUtil.decrypt(client.getPassword()));
             if(StringUtils.isNotBlank(client.getPayPassword())){
                 client.setPayPassword(EncryptAesUtil.decrypt(client.getPayPassword()));
             }
            if(client.getTeamConfigId()!=null&&client.getTeamConfigId()!=0){
                PcTeamConfig config = pcTeamConfigMapper.selectPcTeamConfigById(client.getTeamConfigId());
                if(config!=null){
                    client.setTeamLevel(config.getTeamLevel());
                }
            }
            MpClientFriends friends = new MpClientFriends();
            friends.setClienId(client.getClientId());
            List<MpClientFriends> listF = mpClientFriendsMapper.selectMpClientFriendsList(friends);
            if(listF!=null&&listF.size()!=0){
                MpClient parent = mpClientMapper.selectMpClientByClientId(listF.get(0).getpClientId());
                client.setInviteName(parent.getName());
                client.setInviteMobile(parent.getMobile());
            }
        }
        return list;
    }

    @Override
    public Integer test1() {
        List<MpClient> clients = mpClientMapper.selectMpClientList(new MpClient());
        Integer i =0;
        for (MpClient client: clients) {
            if(StringUtils.isBlank(client.getInviteUrl())){
                //这里设置文本内容
                String text = "http://www.zaoshanghao.net/#/pages/logins/register?inviteCode="+client.getInviteCode()+"";
                // 嵌入二维码的图片路径  可以不写
                String logoPath = "";
                // 生成的二维码的路径及名称
                String destPath = "/usr/local/code";
                //生成二维码
                try {
                    String path = QRCodeUtils.encode(text, logoPath, destPath, true);
                    String url = "http://img.zaoshanghao.net/statics/"+path;
                    client.setInviteUrl(url);
                    mpClientMapper.updateMpClient(client);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            i++;
        }
        return i;
    }

    /**
     * 新增【商城用户】
     *
     * @return 结果
     */
    @Override
    public void insertMpClient(MpRegistForm form)
    {
        String mobile = form.getMobile();
        String code = form.getCode();
        if(StringUtils.isBlank(mobile)){
            throw new ServiceException("手机号不能为空");
        }
        Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
        Matcher m = p.matcher(mobile);
        if(!m.matches()){
            throw new ServiceException("手机号格式不正确");
        }
        MpClient sMpClient = new MpClient();
        sMpClient.setMobile(mobile);
        List<MpClient> sList = mpClientMapper.selectMpClientList(sMpClient);
        if(sList.size()>0){
            throw new ServiceException("手机号已注册");
        }

        //密码验证
        String password = form.getPassword();
        if (StringUtils.isBlank(password)){
            throw new ServiceException("密码不能为空");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        //注册成功,插入用户数据,插入用户上级数据,生成用户邀请码
        String entryPwd = EncryptAesUtil.encrypt(password);
        MpClient client = new MpClient();
        client.setPassword(entryPwd);
        client.setRegistTime(new Date());
        client.setMobile(mobile);
        client.setStatus("1");
        client.setIsVirtual(1);
        client.setGoldBeanBalance(new BigDecimal(0));
        client.setSilverBeanBalance(new BigDecimal(0));
        client.setGoldTransferLimit(new BigDecimal(0));
        client.setSilverTransferLimit(new BigDecimal(0));
        client.setMyEarns("0");
        client.setIsInstitutions(0);
        mpClientMapper.insertMpClient(client);
    }

    /**
     * 修改【商城用户】
     *
     * @param mpClient 【商城用户】
     * @return 结果
     */
    @Override
    public int updateMpClient(MpClient mpClient)
    {
        Integer type = mpClient.getType();
        MpClient updClient = new MpClient();
        updClient.setClientId(mpClient.getClientId());
        updClient.setStatus(mpClient.getStatus());
        if(type==null){
            type=99;
        }
        //修改账号信息
        if(type==1){
            if(StringUtils.isBlank(mpClient.getMobile())){
                throw new ServiceException("手机号不能为空");
            }
            Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
            Matcher m = p.matcher(mpClient.getMobile());
            if(!m.matches()){
                throw new ServiceException("手机号格式不正确");
            }
            MpClient sMpClient = new MpClient();
            sMpClient.setMobile(mpClient.getMobile());
            List<MpClient> sList = selectMpClientList(sMpClient);
            MpClient client = mpClientMapper.selectMpClientByClientId(mpClient.getClientId());
            if(!client.getMobile().equals(sMpClient.getMobile())){
                if(sList.size()>0){
                    throw new ServiceException("手机号已存在");
                }
            }
            String password = mpClient.getPassword();
            if (StringUtils.isBlank(password)){
                throw new ServiceException("密码不能为空");
            }
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                throw new ServiceException("密码长度必须在5到20个字符之间");
            }
            String entryPwd = EncryptAesUtil.encrypt(password);
            updClient.setPassword(entryPwd);
            updClient.setMobile(mpClient.getMobile());
            updClient.setName(mpClient.getName());
        }
        if(type==2){
            if(StringUtils.isBlank(mpClient.getLastMobile())){
                throw new ServiceException("手机号不能为空");
            }
            Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
            Matcher m = p.matcher(mpClient.getLastMobile());
            if(!m.matches()){
                throw new ServiceException("手机号格式不正确");
            }
            MpClient sMpClient = new MpClient();
            sMpClient.setMobile(mpClient.getLastMobile());
            List<MpClient> sList = selectMpClientList(sMpClient);
            if(sList.size()<=0){
                throw new ServiceException("手机号不存在");
            }
            MpClient mpClientOld = selectMpClientByClientId(mpClient.getClientId());
            if(mpClientOld==null){
                throw new ServiceException("修改的商城用户不存在");
            }
            if(mpClient.getLastMobile().equals(mpClientOld.getMobile())){
                throw new ServiceException("上级手机号码不能是自己");
            }
            //验证修改的用户团队等级不能低于自己
            if(mpClientOld.getTeamConfigId()!=null){
                PcTeamConfig pcTeamConfig =  pcTeamConfigMapper.selectPcTeamConfigById(mpClient.getTeamConfigId());
                if(pcTeamConfig!=null){
                    if(sList.get(0).getTeamConfigId()!=null){
                        PcTeamConfig pcTeamConfigS =  pcTeamConfigMapper.selectPcTeamConfigById(sList.get(0).getTeamConfigId());
                        if(pcTeamConfigS!=null){
                           if(pcTeamConfig.getSort()>pcTeamConfigS.getSort()){
                               throw new ServiceException("修改的上级团队等级不能高于自己");
                           }
                        }
                    }
                }
            }
            // 验证修改的上级手机号不能是自己的一二级下级
            MpClientFriends sMpfriends = new MpClientFriends();
            sMpfriends.setpClientId(mpClient.getClientId());
            List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(sMpfriends);
            List<Long> allChildIdList = getUserIds(fList);
            boolean isChild = allChildIdList.stream().anyMatch(e->e.equals(sList.get(0).getClientId()));
            if(isChild){
               throw new ServiceException("修改的手机号码不能是自己的下级");
            }
            //修改自己的上级,如果原本没有上级数据就增加一条
            MpClientFriends uMpfriends = new MpClientFriends();
            uMpfriends.setClienId(mpClient.getClientId());
            List<MpClientFriends> uList = mpClientFriendsMapper.selectMpClientFriendsList(uMpfriends);
            if(uList.size()>0){
                uMpfriends.setpClientId(sList.get(0).getClientId());
                mpClientFriendsMapper.updateMpClientFriends(uMpfriends);
                return uList.size();
            }else{
                uMpfriends.setpClientId(sList.get(0).getClientId());
                return mpClientFriendsMapper.insertMpClientFriends(uMpfriends);
            }

        }
        //修改支付密码
        if(type==3){
            String payPwd = mpClient.getPayPassword();
            if (StringUtils.isNotBlank(payPwd))
            {
                Pattern p = Pattern.compile("\\d{6}");
                Matcher m = p.matcher(payPwd);
                if (payPwd.length()!=UserConstants.PAY_PASSWORD_LENGTH||!m.matches())
                {
                    throw new ServiceException("交易密码长度必须为6位纯数字");
                }
                String entryPwd = EncryptAesUtil.encrypt(payPwd);
                updClient.setPayPassword(entryPwd);
            }
        }
        //修改基础信息
        if(type==4){
           if(mpClient.getGoldTransferLimit()==null){
               throw new ServiceException("金豆转账限额不能为空");
           }
            Pattern p = Pattern.compile("-?[0-9]+.?[0-9]{0,}");
            Matcher m = p.matcher(mpClient.getGoldTransferLimit().toString());
            if (!m.matches())
            {
                throw new ServiceException("金豆转账限额必须为正数");
            }
            if(mpClient.getSilverTransferLimit()==null){
                throw new ServiceException("银藻转账限额不能为空");
            }
            Matcher m1 = p.matcher(mpClient.getSilverTransferLimit().toString());
            if (!m1.matches())
            {
                throw new ServiceException("银藻转账限额必须为正数");
            }
            updClient.setGoldTransferLimit(mpClient.getGoldTransferLimit());
            updClient.setSilverTransferLimit(mpClient.getSilverTransferLimit());
            updClient.setTeamConfigId(mpClient.getTeamConfigId());
            updClient.setBankAddress(mpClient.getBankAddress());
            updClient.setBankAccountName(mpClient.getBankAccountName());
            updClient.setBankName(mpClient.getBankName());
            updClient.setUnionpayNumber(mpClient.getUnionpayNumber());
            updClient.setBankNumber(mpClient.getBankNumber());
            if(mpClient.getIsInstitutions()!=null){
                updClient.setIsInstitutions(mpClient.getIsInstitutions());
                updClient.setIsCert(0);
            }
            updClient.setIdNumber(mpClient.getIdNumber());
        }
        //增加减少金豆银藻数量
        if(type==5){
            //修改金豆
            if(mpClient.getAddType()==1&&mpClient.getAddAmount()!=null){
                MpClient mpClientOld = selectMpClientByClientId(mpClient.getClientId());
                if(mpClientOld==null){
                    throw new ServiceException("修改的商城用户不存在");
                }
                BigDecimal goldBean =  mpClientOld.getGoldBeanBalance()==null?new BigDecimal(0):mpClientOld.getGoldBeanBalance();
                BigDecimal rsGoldBean = goldBean.add(mpClient.getAddAmount());
                if(rsGoldBean.compareTo(new BigDecimal(0))<0){
                    throw new ServiceException("账号金额不能低于0");
                }
                updClient.setGoldBeanBalance(rsGoldBean);
                if(mpClient.getAddAmount().compareTo(new BigDecimal("0"))>0){
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClient.getClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(1l);
                    record.setAmount(mpClient.getAddAmount());
                    record.setContent("后台添加");
                    record.setType(1l);
                    record.setCurrentBalance(updClient.getGoldBeanBalance());
                    record.setRemark(mpClient.getRemark());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);
                }
                if(mpClient.getAddAmount().compareTo(new BigDecimal("0"))<0){
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClient.getClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(0l);
                    record.setAmount(mpClient.getAddAmount());
                    record.setContent("后台扣除");
                    record.setType(1l);
                    record.setCurrentBalance(updClient.getGoldBeanBalance());
                    record.setRemark(mpClient.getRemark());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);
                }
            }
            //修改银藻。
            if(mpClient.getAddType()==2&&mpClient.getAddAmount()!=null) {
                MpClient mpClientOld = selectMpClientByClientId(mpClient.getClientId());
                if (mpClientOld == null) {
                    throw new ServiceException("修改的商城用户不存在");
                }
                BigDecimal silverBean = mpClientOld.getSilverBeanBalance()==null? new BigDecimal(0):mpClientOld.getSilverBeanBalance();
                BigDecimal rsSilverBean = silverBean.add(mpClient.getAddAmount());
                if (rsSilverBean.compareTo(new BigDecimal(0)) < 0) {
                    rsSilverBean = new BigDecimal(0);
                }
                updClient.setSilverBeanBalance(rsSilverBean);
                if(mpClient.getAddAmount().compareTo(new BigDecimal("0"))>0){
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClient.getClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(1l);
                    record.setAmount(mpClient.getAddAmount());
                    record.setContent("后台添加");
                    record.setType(2l);
                    record.setCurrentBalance(updClient.getGoldBeanBalance());
                    record.setRemark(mpClient.getRemark());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);
                }
                if(mpClient.getAddAmount().compareTo(new BigDecimal("0"))<0){
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClient.getClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(0l);
                    record.setAmount(mpClient.getAddAmount());
                    record.setContent("后台扣除");
                    record.setType(2l);
                    record.setCurrentBalance(updClient.getGoldBeanBalance());
                    record.setRemark(mpClient.getRemark());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);
                }
            }
        }

        return mpClientMapper.updateMpClient(updClient);
    }
    //递归出所有用户下级id
    private List<Long> getUserIds(List<MpClientFriends> userIdlist){
        List<Long> ids = new ArrayList<>();
        if(userIdlist!=null && userIdlist.size()>0){
            for(MpClientFriends vo:userIdlist){
                ids.add(vo.getClienId());
                MpClientFriends parentF = new MpClientFriends();
                parentF.setpClientId(vo.getClienId());
                List<MpClientFriends> childs =mpClientFriendsMapper.selectMpClientFriendsList(parentF);
                ids.addAll(getUserIds(childs));
            }
        }
        return ids;
    }

    /**
     * 批量删除【商城用户】
     * 
     * @param clientIds 需要删除的【商城用户】主键
     * @return 结果
     */
    @Override
    public int deleteMpClientByClientIds(Long[] clientIds)
    {
        return mpClientMapper.deleteMpClientByClientIds(clientIds);
    }

    /**
     * 删除【商城用户】信息
     * 
     * @param clientId 【商城用户】主键
     * @return 结果
     */
    @Override
    public int deleteMpClientByClientId(Long clientId)
    {
        return mpClientMapper.deleteMpClientByClientId(clientId);
    }

    @Override
    public List<MpClient> selectMpClientTeamList(MpClient mpClient,Integer type,Integer pageNum,Integer pageSize) {
        if(type==null){
            return new ArrayList<>();
        }
        if(type==1){
            MpClientFriends mpFriends = new MpClientFriends();
            mpFriends.setpClientId(mpClient.getClientId());
            List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(mpFriends);
            if(fList==null||fList.size()==0){
                return new ArrayList<>();
            }
            List<Long> fIds = fList.stream().map(e->e.getClienId()).collect(Collectors.toList());
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<MpClient> first = mpClientMapper.selectMpClientListByIds(mpClient,fIds);
            for (MpClient client: first) {
                if(client.getMyEarns()==null){
                    client.setMyEarns("0");
                }
                if(client.getTeamConfigId()!=null&&client.getTeamConfigId()!=0){
                    PcTeamConfig config = pcTeamConfigMapper.selectPcTeamConfigById(client.getTeamConfigId());
                    if(config!=null){
                        client.setTeamLevel(config.getTeamLevel());
                    }
                }
            }
            return first;
        }
        if(type==2){
            MpClientFriends mpFriends = new MpClientFriends();
            mpFriends.setpClientId(mpClient.getClientId());
            List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(mpFriends);
            if(fList==null||fList.size()==0){
                return new ArrayList<>();
            }
            List<MpClientFriends> sList = new ArrayList<>();
            for (MpClientFriends fr: fList) {
                MpClientFriends mppFriends = new MpClientFriends();
                mppFriends.setpClientId(fr.getClienId());
                List<MpClientFriends> ffList = mpClientFriendsMapper.selectMpClientFriendsList(mppFriends);
                sList.addAll(ffList);
            }
            if(sList.size()==0){
                return new ArrayList<>();
            }
            List<Long> sIds = sList.stream().map(e->e.getClienId()).collect(Collectors.toList());
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<MpClient> second = mpClientMapper.selectMpClientListByIds(mpClient,sIds);
            for (MpClient client: second) {
                if(client.getMyEarns()==null){
                    client.setMyEarns("0");
                }
                if(client.getTeamConfigId()!=null&&client.getTeamConfigId()!=0){
                    PcTeamConfig config = pcTeamConfigMapper.selectPcTeamConfigById(client.getTeamConfigId());
                    if(config!=null){
                        client.setTeamLevel(config.getTeamLevel());
                    }
                }
            }
            return second;
        }
        if(type==3){
            MpClient sClinet = mpClientMapper.selectMpClientByClientId(mpClient.getClientId());
            if(sClinet==null){
                return new ArrayList<>();
            }
            MpClientFriends mpFriends = new MpClientFriends();
            mpFriends.setpClientId(mpClient.getClientId());
            List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(mpFriends);
            if(fList==null||fList.size()==0){
                return new ArrayList<>();
            }
            List<Long> fIds = fList.stream().map(e->e.getClienId()).collect(Collectors.toList());

            List<MpClientFriends> sList = new ArrayList<>();
            for (MpClientFriends fr: fList) {
                MpClientFriends mppFriends = new MpClientFriends();
                mppFriends.setpClientId(fr.getClienId());
                List<MpClientFriends> ffList = mpClientFriendsMapper.selectMpClientFriendsList(mppFriends);
                sList.addAll(ffList);
            }
            if(sList.size()==0){
                return new ArrayList<>();
            }
            List<Long> sIds = sList.stream().map(e->e.getClienId()).collect(Collectors.toList());
            List<Long> myIds = new ArrayList<>();
            myIds.addAll(fIds);
            myIds.addAll(sIds);

            List<Long> allChildIdList = getUserIds(fList);
//            List<Long> reList = allChildIdList.stream().filter(e->!myIds.contains(e)).collect(Collectors.toList());
            List<Long> reList = allChildIdList;
            if(reList==null||reList.size()==0){
                return new ArrayList<>();
            }
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<MpClient> team = mpClientMapper.selectMpClientListByIds(mpClient,reList);
            for (MpClient client: team) {
                if(client.getMyEarns()==null){
                    client.setMyEarns("0");
                }
                if(client.getTeamConfigId()!=null&&client.getTeamConfigId()!=0){
                    PcTeamConfig config = pcTeamConfigMapper.selectPcTeamConfigById(client.getTeamConfigId());
                    if(config!=null){
                        client.setTeamLevel(config.getTeamLevel());
                    }
                }
            }
            return team;
        }
        return null;
    }

    @Override
    public MpClientFriendCount selectMpClientTeamCount(Long clientId) {
        MpClientFriends mpFriends = new MpClientFriends();
        mpFriends.setpClientId(clientId);
        List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(mpFriends);
        MpClientFriendCount count = new MpClientFriendCount();
        count.setFirstCount(fList.size());
        if(fList.size()==0){
            count.setSecondCount(0);
            count.setTeamCount(0);
            return count;
        }
        Integer seCount = 0;
        for (MpClientFriends fr: fList) {
            MpClientFriends mppFriends = new MpClientFriends();
            mppFriends.setpClientId(fr.getClienId());
            List<MpClientFriends> ffList = mpClientFriendsMapper.selectMpClientFriendsList(mppFriends);
            seCount=seCount+ffList.size();
        }
        count.setSecondCount(seCount);
        if(seCount==0){
            count.setTeamCount(0);
            return count;
        }
        List<Long> allChildIdList = getUserIds(fList);
        Integer teamCount =  allChildIdList.size()-fList.size()-seCount;
        count.setTeamCount(teamCount);
        return count;
    }

    @Override
    public List<MpClient> selectMpClientListThree(MpClient mpClient,Integer pageNum,Integer pageSize) {
        List<SysRole> roles = sysRoleMapper.selectRolePermissionByUserId(mpClient.getUserId());
        if(roles.stream().anyMatch(e->e.getRoleName().equals("运营中心"))){
            PcTeamConfig teamConfig = new PcTeamConfig();
            teamConfig.setTeamLevel("v3");
            List<PcTeamConfig> listT = pcTeamConfigMapper.selectPcTeamConfigList(teamConfig);
            mpClient.setTeamConfigId(listT.get(0).getId());
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<MpClient> list = mpClientMapper.selectMpClientList(mpClient);
            return list;
        }
        if(roles.stream().anyMatch(e->e.getRoleName().equals("分公司"))){
            PcCompanyConfig comConfig = new PcCompanyConfig();
            comConfig.setCompanyLevel("运营公司");
            List<PcCompanyConfig> listT = pcCompanyConfigMapper.selectPcCompanyConfigList(comConfig);
            SysUser sysUser = new SysUser();
            sysUser.setCompanyConfigId(listT.get(0).getId());
            sysUser.setUserName(mpClient.getName());
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<SysUser> list = sysUserMapper.selectUserListCenter(sysUser);
           List<MpClient> clients = list.stream().map(e->{
                MpClient client = new MpClient();
                client.setClientId(e.getUserId());
                client.setName(e.getUserName());
                client.setMobile(e.getPhonenumber());
                return client;
            }).collect(Collectors.toList());
            return clients;
        }
        if(roles.stream().anyMatch(e->e.getRoleName().equals("事业部"))){
            PcCompanyConfig comConfig = new PcCompanyConfig();
            comConfig.setCompanyLevel("事业部");
            List<PcCompanyConfig> listT = pcCompanyConfigMapper.selectPcCompanyConfigList(comConfig);
            SysUser sysUser = new SysUser();
            sysUser.setCompanyConfigId(listT.get(0).getId());
            sysUser.setUserName(mpClient.getName());
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<SysUser> list = sysUserMapper.selectUserListBusiness(sysUser);
            List<MpClient> clients = list.stream().map(e->{
                MpClient client = new MpClient();
                client.setClientId(e.getUserId());
                client.setName(e.getUserName());
                client.setMobile(e.getPhonenumber());
                return client;
            }).collect(Collectors.toList());
            return clients;
        }
        return new ArrayList<>();
    }

    @Override
    public List<MpClient> getCenterUsers(MpClient mpClient, Integer pageNum, Integer pageSize) {
        List<SysRole> roles = sysRoleMapper.selectRolePermissionByUserId(mpClient.getUserId());
        if(roles.stream().anyMatch(e->e.getRoleName().equals("运营中心"))){
           PcUserClientFriends friends = new PcUserClientFriends();
           friends.setPcUserId(mpClient.getUserId());
           List<PcUserClientFriends> friends1 = pcUserClientFriendsMapper.selectPcUserClientFriendsList(friends);
           List<Long> clientIds = friends1.stream().map(e->e.getClientTeamId()).collect(Collectors.toList());
           List<MpClient> clients = mpClientMapper.selectMpClientListByIds(mpClient,clientIds);
           return clients;
        }
        if(roles.stream().anyMatch(e->e.getRoleName().equals("分公司"))||roles.stream().anyMatch(e->e.getRoleName().equals("事业部"))){
            PcUserClientFriends friends = new PcUserClientFriends();
            friends.setPcUserId(mpClient.getUserId());
            List<PcUserClientFriends> friends1 = pcUserClientFriendsMapper.selectPcUserClientFriendsList(friends);
            List<Long> userIds = friends1.stream().map(e->e.getPcUserParentId()).collect(Collectors.toList());
            SysUser sysUser = new SysUser();
            sysUser.setUserName(mpClient.getName());
            List<SysUser> users = sysUserMapper.selectUserListByIds(sysUser,userIds);
            List<MpClient> clients = users.stream().map(e->{
                MpClient client = new MpClient();
                client.setClientId(e.getUserId());
                client.setName(e.getUserName());
                client.setMobile(e.getPhonenumber());
                return client;
            }).collect(Collectors.toList());
            return clients;
        }
        return new ArrayList<>();
    }

    @Override
    public void insertClient(MpRegistForm form) {
            String mobile = form.getMobile();
            String code = form.getCode();
            if(StringUtils.isBlank(mobile)){
                throw new ServiceException("手机号不能为空");
            }
            Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
            Matcher m = p.matcher(mobile);
            if(!m.matches()){
                throw new ServiceException("手机号格式不正确");
            }
            MpClient sMpClient = new MpClient();
            sMpClient.setMobile(mobile);
            List<MpClient> sList = mpClientMapper.selectMpClientList(sMpClient);
            if(sList.size()>0){
                throw new ServiceException("手机号已注册");
            }

            //密码验证
            String password = form.getPassword();
            if (StringUtils.isBlank(password)){
                throw new ServiceException("密码不能为空");
            }
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                throw new ServiceException("密码长度必须在5到20个字符之间");
            }

            //邀请码验证
            String inviteCode = form.getInviteCode();
            MpClient parent = new MpClient();
            parent.setInviteCode(inviteCode);
            List<MpClient> parents = mpClientMapper.selectMpClientList(parent);
            if(parents.size()<=0){
                throw new ServiceException("邀请码无效");
            }
            //注册成功,插入用户数据,插入用户上级数据,生成用户邀请码
            String entryPwd = EncryptAesUtil.encrypt(password);
            MpClient client = new MpClient();
            client.setPassword(entryPwd);
            client.setRegistTime(new Date());
            client.setMobile(mobile);
            client.setStatus("1");
            client.setIsVirtual(0);
            client.setGoldBeanBalance(new BigDecimal(0));
            client.setSilverBeanBalance(new BigDecimal(0));
            client.setGoldTransferLimit(new BigDecimal(0));
            client.setSilverTransferLimit(new BigDecimal(0));
            client.setMyEarns("0");
            client.setIsInstitutions(0);
            if(mpClientMapper.insertMpClient(client)>0){
                String inviteCodeMy = ShareCodeUtil.toSerialCode(client.getClientId());
                client.setInviteCode(inviteCodeMy);
                if(mpClientMapper.updateMpClient(client)>0){
                    //这里设置文本内容
                    String text = "http://39.106.24.95:8080/#/pages/logins/register?inviteCode="+inviteCodeMy+"";
                    // 嵌入二维码的图片路径  可以不写
                    String logoPath = "";
                    // 生成的二维码的路径及名称
                    String destPath = "/usr/local/code";
                    //生成二维码
                    try {
                        String path = QRCodeUtils.encode(text, logoPath, destPath, true);
                        String url = "http://39.106.24.95:9401/statics/"+path;
                        client.setInviteUrl(url);
                        mpClientMapper.updateMpClient(client);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    MpClientFriends friends = new MpClientFriends();
                    friends.setClienId(client.getClientId());
                    friends.setpClientId(parents.get(0).getClientId());
                    if(mpClientFriendsMapper.insertMpClientFriends(friends)<=0){
                        throw new ServiceException("添加失败,请稍后再试");
                    }
                }else{
                    throw new ServiceException("添加失败,请稍后再试");
                }
            }else{
                throw new ServiceException("添加失败,请稍后再试");
            }
    }

    @Override
    public Map<String, Object> getReport(Boolean isThisWeek,Boolean isThisMonth,Boolean isToday,String startTime,String endTime) {
        LocalDateTime todayStart = null;
        LocalDateTime todayEnd = null;
        Long  day = null;
        Long endDay = null;
       if(isThisWeek){
            int weekDay = LocalDateTime.now().getDayOfWeek().getValue()-1;
            day = Long.valueOf(-weekDay);
            endDay = Long.valueOf(-weekDay+6);
        }else if(isThisMonth){
            int monthDay = LocalDateTime.now().getDayOfMonth()-1;
            day = Long.valueOf(-monthDay);
            Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
            endDay = Long.valueOf(aCalendar.getActualMaximum(Calendar.DATE)- LocalDateTime.now().getDayOfMonth());
        }else if(isToday){
            day = 0L;
            endDay = 0L;
        }
        if(day!=null){
            todayStart = LocalDateTime.of(LocalDate.now().plusDays(day), LocalTime.MIN);//当天零点
            todayEnd = LocalDateTime.of(LocalDate.now().plusDays(endDay), LocalTime.MAX);//当天零点
            startTime= todayStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            endTime= todayEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        Map<String,Object> map = new HashMap<>();
        MpClient client = new MpClient();
        client.setStartTime(startTime);
        client.setEndTime(endTime);
        client.setIsVirtual(0);
        List<MpClient> clients = mpClientMapper.selectTodayReg(client);
        //获取订单数
        MpClientOrder clientOrder = new MpClientOrder();
        clientOrder.setOrderStatus(201l);
        clientOrder.setStartTime(startTime);
        clientOrder.setEndTime(endTime);
        List<MpClientOrder> orders = mpClientOrderMapper.selectMpClientOrderList(clientOrder);
        Integer allOrderCount = orders.size();
        Integer goldOrderCount =  orders.stream().filter(e->e.getSellType()==1).collect(Collectors.toList()).size();
        Integer silverOrderCount =  orders.stream().filter(e->e.getSellType()==2).collect(Collectors.toList()).size();
        //获取支付交易金额
        MpIncomeRecord incomeRecord = new MpIncomeRecord();
        incomeRecord.setStartTime(startTime);
        incomeRecord.setEndTime(endTime);
        incomeRecord.setIsVirtual(0);
        List<MpIncomeRecord> incomeRecords = mpIncomeRecordMapper.selectMpIncomeRecordListPc(incomeRecord);
        BigDecimal allWxPayCount = incomeRecords.stream().filter(e->e.getType()==3&&e.getAmount()!=null).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取金藻产生总数
        BigDecimal allGoldGetCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==1&&e.getIsIncome()==1&&!e.getContent().contains("转账")&&!e.getContent().contains("提现")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取pc添加金藻总数
        BigDecimal allPcGoldGetCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==1&&e.getIsIncome()==1&&e.getContent().contains("后台添加")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取pc扣除金藻总数
        BigDecimal allPcGoldGiveCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==1&&e.getIsIncome()==0&&e.getContent().contains("后台扣除")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        allGoldGetCount = allGoldGetCount.add(allPcGoldGiveCount);
        BigDecimal pcAllGoldAmount = allPcGoldGetCount.add(allPcGoldGiveCount);
        //获取商城金藻产生总数
        BigDecimal allProGetCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==1&&e.getIsIncome()==1&&e.getContent().contains("购买商品奖励")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取游戏金藻产生总数
        BigDecimal allGameGetCount = allGoldGetCount.subtract(allProGetCount).subtract(pcAllGoldAmount);
        //产生的银藻总数
        BigDecimal allSilverGetCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==2&&e.getIsIncome()==1&&!e.getContent().contains("转账")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取pc添加银藻总数
        BigDecimal allPcSilverGetCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==2&&e.getIsIncome()==1&&e.getContent().contains("后台添加")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //获取pc扣除银藻总数
        BigDecimal allPcSilverGiveCount = incomeRecords.stream().filter(e->e.getAmount()!=null&&e.getType()==2&&e.getIsIncome()==0&&e.getContent().contains("后台扣除")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        allSilverGetCount = allSilverGetCount.add(allPcSilverGiveCount);
        BigDecimal pcAllSilverAmount = allPcSilverGetCount.add(allPcSilverGiveCount);
        //提现数额
        MpCashApply cashApply = new MpCashApply();
        cashApply.setStartTime(startTime);
        cashApply.setEndTime(endTime);
        cashApply.setApprovalStatus("102");
        List<MpCashApply> cashApplies = mpCashApplyMapper.selectMpCashApplyList(cashApply);
        BigDecimal allCashAmount = cashApplies.stream().filter(e->e.getApplyAmount()!=null).collect(Collectors.toList()).stream().map( MpCashApply::getApplyAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        //金藻发放率
        BigDecimal goldPushRate = new BigDecimal(0);
        if(allWxPayCount.compareTo(new BigDecimal(0))>0){
           goldPushRate = allGoldGetCount.divide(allWxPayCount,2,BigDecimal.ROUND_HALF_UP);
        }else{
            goldPushRate = new BigDecimal(0);
        }
        //虚拟号数据
        MpIncomeRecord incomeRecord1 = new MpIncomeRecord();
        incomeRecord1.setStartTime(startTime);
        incomeRecord1.setEndTime(endTime);
        incomeRecord1.setIsVirtual(1);
        List<MpIncomeRecord> incomeRecords1 = mpIncomeRecordMapper.selectMpIncomeRecordListPc(incomeRecord1);
        //产生金藻总数
        BigDecimal allGoldGetCount1 = incomeRecords1.stream().filter(e->e.getAmount()!=null&&e.getType()==1&&e.getIsIncome()==1&&!e.getContent().contains("转账")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //产生银藻总数
        BigDecimal allSilverGetCount1 = incomeRecords1.stream().filter(e->e.getAmount()!=null&&e.getType()==2&&e.getIsIncome()==1&&!e.getContent().contains("转账")).collect(Collectors.toList()).stream().map( MpIncomeRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
        //金藻总数
        MpClient client1 = new MpClient();
        client1.setIsVirtual(1);
        List<MpClient> clients1 = mpClientMapper.selectMpClientList(client1);
        BigDecimal goldAmount = clients1.stream().filter(e->e.getGoldBeanBalance()!=null).collect(Collectors.toList()).stream().map( MpClient::getGoldBeanBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal silVerAmount = clients1.stream().filter(e->e.getSilverBeanBalance()!=null).collect(Collectors.toList()).stream().map( MpClient::getSilverBeanBalance).reduce(BigDecimal.ZERO, BigDecimal::add);

        map.put("clientCount",clients.size());
        map.put("orderCount",allOrderCount);
        map.put("goldOrderCount",goldOrderCount);
        map.put("silverOrderCount",silverOrderCount);
        map.put("wxPayCount",allWxPayCount);
        map.put("allGoldCount",allGoldGetCount);
        map.put("allGoldProCount",allProGetCount);
        map.put("allGoldGameCount",allGameGetCount);
        map.put("allSilverCount",allSilverGetCount);
        map.put("cashAmount",allCashAmount);
        map.put("goldPushRate",goldPushRate);
        map.put("goldCount",goldAmount);
        map.put("silverCount",silVerAmount);
        map.put("allGoldCount1",allGoldGetCount1);
        map.put("allSilverCount1",allSilverGetCount1);
        map.put("pcAllGoldAmount",pcAllGoldAmount);
        map.put("pcAllSilverAmount",pcAllSilverAmount);

        return map;
    }

    public static void main(String[] args) {
        BigDecimal goldPushRate = new BigDecimal("152400").divide(new BigDecimal("7950"),2,BigDecimal.ROUND_HALF_UP);
        System.out.println(goldPushRate);
    }



}
